package com.dzl.finance.service.impl;

import com.dzl.base.service.BaseServiceImpl;
import com.dzl.constant.CommonConstants;
import com.dzl.constant.WelfareFinanceEnum;
import com.dzl.finance.dao.WelfareFinancePaymentMapper;
import com.dzl.finance.pojo.WelfareFinancePayment;
import com.dzl.finance.pojo.query.WelfareFinancePaymentQuery;
import com.dzl.finance.pojo.vo.WelfareFinancePaymentRecordVo;
import com.dzl.finance.pojo.vo.WelfareFinancePaymentSupplierVo;
import com.dzl.finance.pojo.vo.WelfareFinancePaymentVo;
import com.dzl.finance.service.WelfareFinancePaymentRecordService;
import com.dzl.finance.service.WelfareFinancePaymentService;
import com.dzl.util.DateUtil;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ExcelUtil;
import com.dzl.util.ImageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 财务打款信息表(welfare_finance_payment)表服务实现类
 * @author liuguanjun
 * @date 2021-10-12 15:08:39
 */
@Service
public class WelfareFinancePaymentServiceImpl extends BaseServiceImpl<WelfareFinancePayment> implements WelfareFinancePaymentService {

    @Autowired
    private WelfareFinancePaymentMapper mapper;
    @Autowired
    private WelfareFinancePaymentRecordService welfareFinancePaymentRecordService;

    @Override
    public List<Integer> getWelfareFinancePaymentCount(WelfareFinancePaymentQuery query) {
        return mapper.selectWelfareFinancePaymentCount(query);
    }

    @Override
    public PageInfo<WelfareFinancePaymentVo> getWelfareFinancePaymentListPage(WelfareFinancePaymentQuery query) {
        if(EmptyUtils.isNotEmpty(query.getPaymentNo())){
            query.setPaymentNo(query.getPaymentNo().trim());
        }
        PageHelper.startPage(query);
        List<WelfareFinancePaymentVo> list = mapper.selectWelfareFinancePaymentList(query);
        for (WelfareFinancePaymentVo welfareFinancePayment : list) {
            welfareFinancePayment.setRemark(EmptyUtils.isEmpty(welfareFinancePayment.getRemark())?"":welfareFinancePayment.getRemark());
            //供应商维度订单
            Map<Integer, List<WelfareFinancePaymentRecordVo>> supplierMap = new HashMap<Integer, List<WelfareFinancePaymentRecordVo>>();
            //查询该批次所有订单
            query.setPaymentId(welfareFinancePayment.getId());
            List<WelfareFinancePaymentRecordVo> orderGoodsList = welfareFinancePaymentRecordService.selectWelfareFinancePaymentRecordByPaymentId(query);
            if(EmptyUtils.isNotEmpty(orderGoodsList)){
                for (WelfareFinancePaymentRecordVo record : orderGoodsList) {
                    // 拼接订单商品属性
                    StringBuilder goodsDetail = new StringBuilder();
                    if (EmptyUtils.isNotEmpty(record.getFirstDetailName())) {
                        goodsDetail.append(record.getFirstDetailName());
                    }
                    if (EmptyUtils.isNotEmpty(record.getSecondDetailName())) {
                        goodsDetail.append("/");
                        goodsDetail.append(record.getSecondDetailName());
                    }
                    if (EmptyUtils.isNotEmpty(record.getThirdDetailName())) {
                        goodsDetail.append("/");
                        goodsDetail.append(record.getThirdDetailName());
                    }
                    record.setAttrName(goodsDetail.toString());
                    List<WelfareFinancePaymentRecordVo> detailList = supplierMap.get(record.getSupplierId());
                    if(EmptyUtils.isEmpty(detailList)){
                        detailList = new ArrayList<WelfareFinancePaymentRecordVo>();
                    }
                    detailList.add(record);
                    supplierMap.put(record.getSupplierId(), detailList);
                }
            }
            List<WelfareFinancePaymentSupplierVo> welfareFinancePaymentSupplierVoList = new ArrayList<>();
            if(supplierMap.size()>0) {
                for (Map.Entry<Integer, List<WelfareFinancePaymentRecordVo>> entry : supplierMap.entrySet()) {
                    WelfareFinancePaymentSupplierVo welfareFinancePaymentSupplierVo = new WelfareFinancePaymentSupplierVo();
                    WelfareFinancePaymentRecordVo welfareFinancePaymentRecordVo = entry.getValue().get(0);
                    BeanUtils.copyProperties(welfareFinancePaymentRecordVo,welfareFinancePaymentSupplierVo);
                    welfareFinancePaymentSupplierVo.setPaymentType(EmptyUtils.isEmpty(welfareFinancePaymentSupplierVo.getPaymentType())?5:welfareFinancePaymentSupplierVo.getPaymentType());
                    welfareFinancePaymentSupplierVo.setPaymentStatus(EmptyUtils.isEmpty(welfareFinancePaymentSupplierVo.getPaymentStatus())?1:welfareFinancePaymentSupplierVo.getPaymentStatus());
                    welfareFinancePaymentSupplierVo.setOrderGoodsList(entry.getValue());
                    //汇总订单id：orderIds
                    ArrayList<Integer> orderIds = new ArrayList<>();
                    //供应商维度计算成本总价
                    BigDecimal totalAmount = BigDecimal.ZERO;
                    for (WelfareFinancePaymentRecordVo record : entry.getValue()) {
                        totalAmount = totalAmount.add(record.getCostTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        if(!orderIds.contains(record.getOrderId())){
                            orderIds.add(record.getOrderId());
                        }
                    }
                    StringBuilder orderIds_ = new StringBuilder();
                    for (Integer orderId : orderIds) {
                        orderIds_.append(welfareFinancePayment.getId()+"_"+orderId+",");
                    }
                    welfareFinancePaymentSupplierVo.setOrderIds(orderIds_.substring(0,orderIds_.length()-1));
                    welfareFinancePaymentSupplierVo.setTotalAmount(totalAmount);
                    welfareFinancePaymentSupplierVo.setPaymentFile(ImageUtils.setImageSrc(welfareFinancePaymentSupplierVo.getPaymentFile()));
                    welfareFinancePaymentSupplierVoList.add(welfareFinancePaymentSupplierVo);
                }
            }
            welfareFinancePayment.setOrderSupplierList(welfareFinancePaymentSupplierVoList);
        }
        PageInfo<WelfareFinancePaymentVo> page = new PageInfo<WelfareFinancePaymentVo>(list);
        return page;
    }

    //打款日期、供应商名称、订单日期、商品名称、商品规格、成本价、数量、合计价格、账户类型、账户名称、银行账户、开户行、申请人
    @Override
    public void batchExportPaymentInfo(String orderIds, HttpServletResponse res) {
        //StringBuffer orderIds_ = new StringBuffer();//拼接订单id，1552,1553
        String[] orderIdList = orderIds.split(",");
        List<WelfareFinancePaymentRecordVo> list = new ArrayList<>();
        WelfareFinancePaymentQuery query = new WelfareFinancePaymentQuery();
        for (String orderId:orderIdList) {
            //orderIds_.append(orderId.split("_")[1]+",");//拼接订单id
            Integer pId = Integer.valueOf(orderId.split("_")[0]);
            Integer oId = Integer.valueOf(orderId.split("_")[1]);
            query.setPaymentId(pId);
            query.setOrderId(oId);
            List<WelfareFinancePaymentRecordVo> list_ =  welfareFinancePaymentRecordService.selectWelfareFinancePaymentRecordByPaymentId(query);
            list.addAll(list_);
        }
        List<List<String>> data = new ArrayList<>();
        if(EmptyUtils.isNotEmpty(list)){
            for (WelfareFinancePaymentRecordVo record : list) {
                List<String> rowData = new ArrayList();
                rowData.add(record.getPaymentNo());
                // 拼接订单商品属性
                StringBuilder goodsDetail = new StringBuilder();
                if (EmptyUtils.isNotEmpty(record.getFirstDetailName())) {
                    goodsDetail.append(record.getFirstDetailName());
                }
                if (EmptyUtils.isNotEmpty(record.getSecondDetailName())) {
                    goodsDetail.append("/");
                    goodsDetail.append(record.getSecondDetailName());
                }
                if (EmptyUtils.isNotEmpty(record.getThirdDetailName())) {
                    goodsDetail.append("/");
                    goodsDetail.append(record.getThirdDetailName());
                }
                record.setAttrName(goodsDetail.toString());
                if(EmptyUtils.isNotEmpty(record.getBankAccountType())){
                    if(record.getBankAccountType().equals(WelfareFinanceEnum.SUPPLIER_PAYMENT_TYPE_CORPORATE+"")){
                        record.setBankAccountType("对公账户");
                    }else if(record.getBankAccountType().equals(WelfareFinanceEnum.SUPPLIER_PAYMENT_TYPE_ALIPAY+"")){
                        record.setBankAccountType("支付宝");
                    }else if(record.getBankAccountType().equals(WelfareFinanceEnum.SUPPLIER_PAYMENT_TYPE_OTHER+"")){
                        record.setBankAccountType("其他");
                    }
                }
                if(EmptyUtils.isEmpty(record.getBankAccountType())){
                    record.setBankAccountType("未设置");
                }
                if(EmptyUtils.isNotEmpty(record.getPaymentType())){
                    if(record.getPaymentType().equals(WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_REAL_TIME.getCode())){
                        record.setPaymentTypeName("实时结算");
                    }else if(record.getPaymentType().equals(WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_MONTH.getCode())){
                        record.setPaymentTypeName("月结算");
                    }else if(record.getPaymentType().equals(WelfareFinanceEnum.FINANCE_PAYMENT_TYPE_WEEK.getCode())){
                        record.setPaymentTypeName("周结算");
                    }
                }
                if(EmptyUtils.isEmpty(record.getPaymentTypeName())){
                    record.setPaymentTypeName("未设置");
                }
                String paymentTime = "";
                if(record.getPaymentTime()!=null){
                    paymentTime = DateUtil.format2DateTime(record.getPaymentTime());
                }
                rowData.add(DateUtil.format2DateTime(record.getFinanceTime()));
                rowData.add(record.getSupplierName());
                rowData.add(DateUtil.format2DateTime(record.getOrderTime()));
                rowData.add(record.getOrderNo());
                rowData.add(record.getGoodsName());
                rowData.add(record.getAttrName());
                rowData.add(record.getCostPrice().toString());
                rowData.add(record.getGoodsQuantity().toString());
                rowData.add(record.getCostTotalPrice().toString());
                rowData.add(record.getPaymentTypeName());
                rowData.add(paymentTime);
                rowData.add(record.getBankAccountType());
                rowData.add(record.getBankAccountName());
                rowData.add(record.getBankAccount());
                rowData.add(record.getBankName());
                rowData.add(record.getPaymentApplyUserName());
                data.add(rowData);
            }
        }
        OutputStream os = null;
        try{
            String[] headers = {"打款编号","申请打款日期","供应商名称","订单日期","订单号","商品名称","商品规格","成本价","数量","合计价格","打款类型","打款日期","账户类型","账户名称","银行账户","开户行","申请人"};
            HSSFWorkbook workbook = new HSSFWorkbook();
            String fileName = "财务打款订单" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
            res.setHeader("Content-disposition", "attachment; filename=" + fileName);
            res.setContentType("application/vnd.ms-excel;charset=utf-8");
            os = res.getOutputStream();
            ExcelUtil.exportExcel(workbook, 0, "Page1", headers, data, os);
            workbook.write(os);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}